<template>
	<view>
		<view>
			<table-title content="空调加时办理表详情"></table-title>
			<view class="record-id">单号：{{processNo}}</view>
			<view class="in-center">
				<small-title content="基本资料"></small-title>
				<view class="state-bar">
					<view class="state-msg">{{state}}</view>
				</view>
			</view>
			<view class="item-table">
				<view-item name="租户名称" :value="userMsg.userCompany"></view-item>
				<view-item name="楼盘" :value="userMsg.userBuilding"></view-item>
				<view-item name="楼层" :value="userMsg.userFloor"></view-item>
				<view-item name="房间号" :value="userMsg.userRoom" :isLast="true"></view-item>
			</view>
			<small-title content="加时日期及时间"></small-title>
			<!-- <uni-section :title="'日期时间范围用法：' + '[' + datetimerange + ']' " type="line"></uni-section> -->
			<view class="time-table">
				<uni-datetime-picker @change="timeChange" :disabled="status!==-1" :hideSecond="true" v-model="datetimerange" type="datetimerange"
					 rangeSeparator="至" />
			</view>
			<view class="small-title">总时长：{{hours}} 小时</view>
			<view class="small-title">费用合计：{{spend}} 元</view>
			<small-title :isNeed="true" content="选择工程负责人"></small-title>
			<view class="small-title">
				<select-lay :disabled="status!==0" :value="tval" name="name" :options="datalist" @selectitem="selectitem"></select-lay>
			</view>
			<small-title content="处理进度"></small-title>
			
			<proccess-bar v-if="processFlag" :proccessList="proccessListDefult"></proccess-bar>
			<view v-if="status===0 && userRightDetail.airCondition.opeCommRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="allot">发起指派</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="status===7 && userRightDetail.airCondition.engCommRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="confirmOpen">已制定计划</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="status===4 && userRightDetail.airCondition.engCommRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="confirmClose">空调已关闭</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="status===3 && userRightDetail.airCondition.opeCommRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="verify(0)">审核通过</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="open">驳回</button>
				</view>
			</view>
			<view v-if="status===5 && userRightDetail.airCondition.refundRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="refund(processNo,'Air conditioning overtime cancellation',0.01)">确认退款</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view style="height: 200rpx;"></view>
		</view>
		<uni-popup ref="popup" type="dialog">
		    <uni-popup-dialog mode="input" message="成功消息" title="请输入驳回理由" :duration="2000" :before-close="true" @close="close" @confirm="confirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>		

<script>
	import {
		ONLINE_SERVER_ADDRESS_BASE_2,
		syncGetOrder,
		syncGetSysUsr,
		syncGetSysUsrInfo,
	} from "../../../util/network.js"
	import {
		processHistoryList
	} from "../../../util/common.js"
	import {
		authRouterGuard,
		homeInitLocation,
		uniRedirect,
		uniSetToken,
		uniGetStorageSync
	} from '../../../util/funcs';
	export default{
		data() {
			return {
				processFlag:false,
				userRightDetail:'',
				token:'',
				recordId: '待分配',                                                         //单号
				processNo:'待分配',
				state: '已受理',																	   //状态
				status: -1,
				nopassReasons:'楼层管家审核空调加时通过',
				userMsg:{'userName':'','userPhone':'','userCompany':'','userBuilding':'',
					'userFloor':'','userRoom':''},
				hours: 0,                                                                          //加时总时长
				spend:0,                                                                           //加时总费用
				datetimerange: ['', ''],                                                           //加时区间
				payway: [true, false],                                                            //支付方式
				proccessList:[
					{'type':'firstCanvas','commentMsg':'发起申请','time':'2021-01-01 01:01:11'},
					{'type':'middleCanvas','commentMsg':'受理','time':'2020-02-02 02:02:22'},
					{'type':'lastCanvas','commentMsg':'办结','time':'2020-03-03 03:33:33'}
				],                                                                                 //处理进度
				proccessListDefult:[],
				unitPrice: 20,                                                                     //加时单价，只在初次申请时通过查询对应区域价格获取值
				//模拟数据列表
				datalist: [],
				//模拟初始数据
				tval: "value2",
			}
		},
		methods: {
			open() {
				this.$refs.popup.open()
			},
			/**
			 * 点击取消按钮触发
			 * @param {Object} done
			 */
			close() {
				// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
				// ...
				this.$refs.popup.close()
			},
			/**
			 * 点击确认按钮触发
			 * @param {Object} done
			 * @param {Object} value
			 */
			confirm(value) {
				this.$refs.popup.close()
				if(value == ""){
					uni.showModal({
						content:'理由不能为空',
						showCancel:false
					});
					this.$refs.popup.close()
				}else{
					if(this.userRightDetail.knotCommission.primeAuth == 1){
						this.nopassReasons = "运营主管已驳回，原因：" + value
					}else{
						this.nopassReasons = "楼层管家已驳回，原因：" + value
					}
					this.verify(1)
					// TODO 做一些其他的事情，手动执行 close 才会关闭对话框
					// ...
					this.$refs.popup.close()
				}
			},
			selectitem(index, item) {
				console.log(item)
				if (index >= 0) {
					this.tval = item.value;
				} else {
					this.tval = ""
				}
			},
			
			/*
			功能：选择支付方式
			参数：无
			*/
			changePayway(e){
				console.log('-change事件:', e.detail.value)
				if(e.detail.value == "alipay"){
					this.payway=[true,false];
				}else{
					this.payway=[false,true];
				}
			},
			
			/*
			功能：计算加时费用
			参数：无
			*/
			timeChange(e){
				// console.log('-change事件:', e)
				let timeSum = Date.parse(e[1].replace(/-/g, '/')) - Date.parse(e[0].replace(/-/g, '/'))
				//计算出相差天数  
				var days=Math.floor(timeSum/(24*3600*1000))  
				//计算出小时数  
				var leave1=timeSum%(24*3600*1000)    //计算天数后剩余的毫秒数  
				var hours=Math.floor(leave1/(3600*1000))  
				//计算相差分钟数  
				var leave2=leave1%(3600*1000)        //计算小时数后剩余的毫秒数  
				var minutes=Math.floor(leave2/(60*1000))  
				if(minutes > 0){
					hours = hours + 1 + days * 24
				}else{
					hours = hours + days * 24
				}
				this.hours = hours
				this.spend = hours * 20
			},
			verify(status){
				console.log("[info]","空调加时取消审核：" + this.recordId)
				if(status == 0){
					if(this.userRightDetail.knotCommission.primeAuth == 1){
						this.nopassReasons = "运营主管已审核通过"
					}else{
						this.nopassReasons = "楼层管家已审核通过"
					}
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/overtime-ac/verify/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						nopassReasons:this.nopassReasons,
						verifyResult:status,
						commentMsg: this.nopassReasons,                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("空调加时取消审核调用失败")
					}
				})
			},
			confirmOpen(){
				console.log("[info]","开启空调计划：" + this.recordId)
				if(this.userRightDetail.repair.primeAuth == 7){
					this.nopassReasons = "工程主管已制定空调加时计划"
				}else{
					this.nopassReasons = "工程专员已制定空调加时计划"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/overtime-ac/confirm-open/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						commentMsg: this.nopassReasons                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("空调加时计划制定调用失败")
					}
				})
			},
			confirmClose(){
				console.log("[info]","关闭空调计划：" + this.recordId)
				if(this.userRightDetail.repair.primeAuth == 7){
					this.nopassReasons = "工程主管已关闭空调加时计划"
				}else{
					this.nopassReasons = "工程专员已关闭空调加时计划"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/overtime-ac/confirm-close/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						commentMsg: this.nopassReasons                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("空调加时计划关闭调用失败")
					}
				})
			},
			refund(processNo,reason,refundAmount){
				let _this = this
				uni.showModal({
					title: '提示',
					content: '确认是否退款？',
					success: function (R) {
						if (R.confirm) {
							uni.request({
								url:`${ONLINE_SERVER_ADDRESS_BASE_2}/pay/refund`,
								header: {
									'Authorization': _this.token,
								},
								data: {
									processNo:processNo,
									reason:reason,
									refundAmount:Number(_this.spend),                       //操作信息
								},
								method:'POST',
								success: function (res) {
									console.log("空调加时退款调用",res)
									if(res.data.code == 200){
										_this.confirmRefund()
									}else{
										uni.showModal({
											content:'退款调用失败,请联系IT人员',
											showCancel:false
										})
									}
								},
								fail: (res) => {
									console.log("空调加时退款调用失败")
								}
							})
						} else if (R.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			confirmRefund(){
				console.log("[info]","空调加时退款：" + this.recordId)
				if(this.userRightDetail.exchangeRent.primeAuth == 5){
					this.nopassReasons = "财务主管已确认空调加时款项原路退回"
				}else{
					this.nopassReasons = "财务专员已确认空调加时款项原路退回"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/overtime-ac/confirm-refund/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						commentMsg: this.nopassReasons                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("空调加时款项已原路退回调用失败")
					}
				})
			},
			allot(){
				console.log("[info]","空调加时指派：" + this.recordId)
				if(!(parseInt(this.tval) > 0)){
					uni.showModal({
						content:'请选择工程人员',
						showCancel:false
					});
					return -1
				}
				let comment = ''
				if(this.userRightDetail.knotCommission.primeAuth == 1){
					comment = "运营主管已推送给工程办理"
				}else{
					comment = "楼层管家已推送给工程办理"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/overtime-ac/allot/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						allotType:0,
						userId:parseInt(this.tval),
						commentMsg: comment,                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("空调加时指派调用失败")
					}
				})
			},
			getOrder(){
				let a = syncGetOrder("overtime-ac/show/" + this.recordId)
				 a.then((res)=>{
					 console.log("异步",res)
					 if(res.data.code == 200){
						 this.status = parseInt(res.data.data.status)
						 switch(this.status) {
						 	 case 0:
						 		this.state = "待指派工程"
						 		break;
						 	 case 1:
						 		this.state = "计划执行中"
						 		break;
						 	 case 2:
						 		this.state = "加时完毕"
						 		break;
						 	 case 3:
						 		this.state = "取消待审核"
						 		break;
						 	 case 4:
						 		this.state = "待工程关闭"
						 		break;
						 	 case 5:
						 		this.state = "待财务退款"
						 		break;
						 	 case 6:
						 		this.state = "加时已取消"
						 		break;
						 	 case 7:
						 		this.state = "待工程确认"
						 		break;
						      default:
						 	    this.status = -1
						        this.state = "待申请"
						 } 
						 this.userMsg.userCompany = res.data.data.createUserInfo.name
						 this.userMsg.userBuilding = res.data.data.createUserInfo.title
						 this.userMsg.userFloor = res.data.data.createUserInfo.floor
						 this.userMsg.userRoom = res.data.data.createUserInfo.houseNumber
						 this.$set(this.datetimerange, 0, res.data.data.startTime)
						 this.$set(this.datetimerange, 1, res.data.data.endTime)
						 this.hours = res.data.data.hours
						 this.spend = res.data.data.price
						 this.processNo = res.data.data.processNo
						 this.proccessListDefult = processHistoryList(res.data.data.processDetail)
						 this.processFlag = true
						 if(this.status != 0){
							 console.log("systemuser/show/",parseInt(res.data.data.engineerSpecialistId))
						 	let b = syncGetSysUsrInfo("systemuser/show/" + parseInt(res.data.data.engineerSpecialistId));
							// let b = syncGetSysUsrInfo("systemuser/show/10209");
						 	b.then((v)=>{
						 		 console.log("异步userinfo",v)
						 		 if(v.data.code == 200){
									let temp = {label: "",value: ""}
									temp.label = v.data.data.name
									temp.value = res.data.data.engineerSpecialistId
									this.datalist.push(temp)
						 			this.tval = temp.value
						 			this.$forceUpdate()
						 		}
						 	})
						 }
						 if(this.status == 0){ //如果是待指派状态 则按区域查询工程专员
						 	var areaId = uni.getStorageSync("currentUser").area_id
						 	console.log("查询工程人员1",areaId)
						 	let a = syncGetSysUsr("systemuser/area-auth/users", areaId, 8);
						 	a.then((res)=>{
						 		 console.log("查询工程人员",res)
						 		 if(res.data.code == 200){
						 			let resList = res.data.data.systemUserList
						 			resList.forEach((item,key) => {
						 				let temp = {label: "",value: ""}
						 				temp.label = item.name
						 				temp.value = item.id.toString()
						 				this.datalist.push(temp)
						 			});
						 			this.$forceUpdate()
						 		}
						 	})
						 }
						 this.$forceUpdate()
					}
				})
			},
			back(){
				uni.navigateBack()
			}
		},
		onLoad(option) {
			//传入单号
			if(uni.getStorageSync('userinfo') != null){
				this.userRightDetail = uni.getStorageSync("userRight")
				this.recordId = option.id
				// this.state = option.state
				this.token = uni.getStorageSync('token')
			}else{
				uni.navigateTo('../../login/login')
			}
		},
		mounted() {
			this.getOrder()
		}
	}
</script>

<style>
	page{
		background-color: #ffffff
	}
	.record-id{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.state-bar{
		display: flex;
		align-items: center;
		color: #FFFFFF;
		background-color: #DD524D;
		width: 260rpx;
		justify-content: center;
		margin-left: auto;
		margin-right: 50rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 50rpx;
	}
	.state-msg{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.item-table{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.mix-button{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.left-part{
		float: right;
	}
	.right-part{
		float: left;
	}
	.left-button{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button{
		background-color: #0000FF;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.in-center{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.add-button {
		border-width: 0px;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0 40rpx 250rpx;
		height: 50rpx;
		width: 250rpx;
		display: flex;
		color: #22B242;
	}
	.payway-style {
		display: flex;
		flex-direction: column;
		width: 650rpx;
	}
	.first-radio {
		height: 100rpx;
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		padding-left: 25rpx;
		border: solid 0rpx #C8C7CC;
		border-bottom: none;
		border-right: none;
	}
	.second-radio {
		height: 100rpx;
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		padding-left: 25rpx;
		border: solid 0rpx #C8C7CC;
		border-right: none;
		width: 50rpx;
	}
	.payway-choice {
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		border: solid 0rpx #C8C7CC;
		width: 600rpx;
		border-left: none;
	}
	.payway-logo {
		width: 50rpx;
		height: 50rpx;
		margin: 0 25rpx 0 25rpx;
	}
	.small-title{
		margin: 20rpx 0 20rpx 50rpx;
		width: 87%;
	}
	.time-table{
		margin: 20rpx 20rpx 20rpx 50rpx;
		width: 87%;
	}
</style>
